/***************************************************************************
 *   Copyright (C) 2006 by Sergey Melderis   *
 *   sergey.melderis@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "wordquizwriter.h"
#include <kconfig.h>
#include <qfile.h>
#include <qdom.h>
#include <qmessagebox.h>
#include "filesprefs.h"
WordQuizWriter::WordQuizWriter(QObject * parent, const char * name)
 : QObject(parent, name)
{
}

WordQuizWriter::~WordQuizWriter()
{
}


void WordQuizWriter::reconfigure()
{
    mFilesMap = FilesPrefs::self().keyUrlItems();
}


void WordQuizWriter::addWord(const QString &fileKey,
    const QString &word, const QString &translation)
{
    QString fileName = mFilesMap[fileKey];
    QDomDocument doc;
    QFile file(fileName);
    QString errorStr;
    if (!file.exists()) {
        return /* void */ showErrorDialog("File " + fileName + " does not exist");
    }
    if (!file.open( IO_ReadWrite )) {
        return /* void */ showErrorDialog("Error opening file " + fileName);
    }
    if (!doc.setContent(&file)) {
        file.close();
        return /* void */ showErrorDialog("Error parsing file " + fileName);
    }
    file.close();
    // Create a new null node.
    QDomElement parentCandidate;
    if (!isWordExist(doc, word, translation, parentCandidate)) {
        if (!parentCandidate.isNull())
            addDataToElement(doc, parentCandidate, word, translation);
        else
            addWordToDocument(doc, word, translation);
        const int IndentSize = 2;
        QString error;
        file.open(IO_WriteOnly);
        QTextStream out(&file);
        doc.save(out, IndentSize);
        file.close();
        emit addWordCompleted(word + " - " + translation + "\n was added to " + fileKey);
    } else
        emit addWordCompleted("\"" + word + " - " + translation + "\"" +
                         " is already in " + fileKey);
    file.close();
}


void WordQuizWriter::showErrorDialog(const QString &errorMessage)
{
    QMessageBox::warning(0,
                         "KLingvoTranslator",
                         errorMessage,
                         QMessageBox::Ok,
                         QMessageBox::NoButton);
}


/**
 * Function returns returns true if the current word and translation is already exists
    in the document. parentCandidate will reference a suitable parent candidate node to
    insert a new word and translation. The first node that is like: <e><o/><t/></e> .
    If no node is found the reference in unchanged. Should be null node.
*/
bool WordQuizWriter::isWordExist(const QDomDocument &doc, const QString &word,
                                    const QString &transl, QDomElement &parentCandidate)
{
    QDomNodeList list = doc.elementsByTagName("e");
    int length = list.length();
    for (int i = 0; i < length; i++) {
        QDomElement e = list.item(i).toElement();
        if (e.hasChildNodes()) {
              QDomElement o = e.firstChild().toElement();
              QDomElement t = e.lastChild().toElement();
              if (!o.hasChildNodes() && !t.hasChildNodes()) {
                  if (parentCandidate.isNull())
                      parentCandidate = e;
              } else {
                  if (o.firstChild().isText() && t.firstChild().isText()) {
                      if (o.firstChild().toText().data() == word &&
                         t.firstChild().toText().data() == transl )
                          return true;

                  }
              }
        }
    }
    return false;
}

void WordQuizWriter::addWordToDocument(QDomDocument &doc, const QString &orig, const QString &tran)
{
    QDomElement root = doc.documentElement();
    QDomElement element = doc.createElement("e");
    root.appendChild(element);
    QDomElement origElement = doc.createElement("o");
    QDomText origText = doc.createTextNode(orig);
    origElement.appendChild(origText);
    element.appendChild(origElement);
    QDomElement translElement = doc.createElement("t");
    element.appendChild(translElement);
    QDomText trText = doc.createTextNode(tran);
    translElement.appendChild(trText);
}

void WordQuizWriter::addDataToElement(QDomDocument &doc, QDomElement &element,
                                          const QString &orig, const QString &tran)
{
    QDomText oDomText = doc.createTextNode(orig);
    QDomText tDomText = doc.createTextNode(tran);
    element.firstChild().appendChild(oDomText);
    element.lastChild().appendChild(tDomText);
}

#include "wordquizwriter.moc"


